from fastapi import APIRouter,Form
from lisdemo.sql_app import crud, schemas
from lisdemo.sql_app.database  import get_db
from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session


router = APIRouter()






@router.get("/")
async def read_users():
    return [{"username": "Foo"}, {"username": "Bar"}]


@router.get("/me")
async def read_user_me():
    return {"username": "fakecurrentuser"}


@router.get("/{username}")
async def read_user(username: str):
    return {"username": username}


@router.get("/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    print(db_user.to_dict())
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user.to_dict()


@router.get("/allusers/")
def readall_user(db: Session = Depends(get_db)):
    db_user = crud.getall_user(db)
    alluser = [i.to_dict() for i in db_user]
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return alluser

@router.post('/create')
def create_user(db:Session = Depends(get_db),email:str=Form(...),phone:str=Form(...),password:str=Form(...)):
    hashed_password='lisdemo'+password+'lisdemo'
    try:
        crud.create_user(db, schemas.UserCreate(email=email, phone=phone, hashed_password=hashed_password))
        return 'create sussess'
    except:
        return 'create failed'

@router.put('/update')
def create_user(user: schemas.UserCreate, db:Session = Depends(get_db)):
    hashed_password='lisdemo'+user.hashed_password+'lisdemo'
    try:
        crud.update_user(db, user)
        return 'create sussess'
    except:
        return 'create failed'
